package com.sicheng.algorithm.string;

/**
 * @author zsc
 * @version 1.0
 * @date 2021/9/18 10:04
 */
public class LeftRotateString {

    /**
     * 题目描述
     * 将字符串 S 从第 K 位置分隔成两个子字符串，并交换这两个子字符串的位置。
     * <p>
     * Input:
     * S="abcXYZdef"
     * K=3
     * <p>
     * Output:
     * "XYZdefabc"
     */


    public static void main(String[] args) {
        String string = new LeftRotateString().leftRotateString("abcXYZdef", 9);
        System.out.println(string);
    }

    public String leftRotateString(String content, int k) {

        if (content == null || content.length() == 0 || k < 0 || k > content.length())
            return null;

        char[] chars = content.toCharArray();
        if (k == content.length()) {
            return String.valueOf(chars);
        }
        reverse(chars, 0, k - 1);
        reverse(chars, k, content.length() - 1);
        reverse(chars, 0, content.length() - 1);

        return String.valueOf(chars);
    }

    /**
     *  字符串局部反转
     */
    public static void reverse(char[] chars, int start, int end) {
        while (start < end) {
            swap(chars, start, end);
            start++;
            end--;
        }
    }

    public static void swap(char[] chars, int start, int end) {
        char temp;
        temp = chars[start];
        chars[start] = chars[end];
        chars[end] = temp;
    }


}
